#include <QAudioOutput>
#include <QFile>
#include "aisaudiorender.h"

AISAudioRender::AISAudioRender(QWidget *parent):
    QWidget(parent)
{
}

bool AISAudioRender::play(const QString &filePath)
{
    audioFile = new QFile(filePath);
    if (audioFile->open(QFile::ReadOnly))
    {
        QAudioFormat format;
        format.setSampleRate(16000);
        format.setChannelCount(1);
        format.setSampleSize(16);
        format.setCodec("audio/pcm");
        format.setByteOrder(QAudioFormat::LittleEndian);
        format.setSampleType(QAudioFormat::UnSignedInt);

        QAudioDeviceInfo info(QAudioDeviceInfo::defaultInputDevice());
        if (! info.isFormatSupported(format))
        {
            return false;
        }

        audioOutput = new QAudioOutput(format, this);
        connect(audioOutput, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State)));
        audioOutput->start(audioFile);
        return true;
    }
    return false;
}

void AISAudioRender::handleStateChanged(QAudio::State newState)
{
    switch (newState)
    {
    case QAudio::IdleState:
        audioOutput->stop();
        delete audioOutput;
        audioOutput = NULL;
        audioFile->close();
        audioFile = NULL;
        break;
    case QAudio::StoppedState:
        if (QAudio::NoError != audioOutput->error())
        {
            // error handling
        }
    default:
        break;
    }
}
